<?php

$loader->requireOnce('includes/RadQueue/RadQueueProcessor.class.php');
$loader->requireOnce('includes/RadConnector/InPatientRadConnector.class.php');
$loader->requireOnce('includes/RadConnector/OutPatientRadConnector.class.php');
$loader->requireOnce('includes/RadConnector/RadConnectorFactory.class.php');
$loader->requireOnce('includes/RadUtils.class.php');
class C_RadQueue  extends Controller {
    private $logger ;
    function __construct($template_mod = "general") {
        parent::__construct($template_mod);
        parent::Controller();
        if (Celini::getCurrentController() == 'RadQueue') {
            $menu =& Menu::getInstance();
            $menu->currentSection = 'patient';
        }
        $this->logger = LoggerManager::getLogger('module.dept_rad.controllers.C_RadQueue');
        $this->template_mod = $template_mod;
        $this->view->path="rad_queue";
    }

    public function actionRenderQueue() {
    	$this->logger->info("Start action renderQueue");
    	$html = '';
    	try {
            // Rooms of current departmnent
            $login2Dept =  $this->_me->get_department_id();
	        $roomList   =  ORDataObject::factory('Room')->getAllRooms($login2Dept, true);
            $this->assign('roomList', $roomList);
            // Default room
            $paraConfig  =   ORDataObject::factory('ParacliniqueConfig')->getParaclinicConfig(EnumerationConstant::PARACLINIC_XRAY);
            $this->assign('defaultRoom', $paraConfig['room_id']);
            // Patient types
	    	$patientType = Utils::getEnumArrayKey(EnumerationConstant::PATIENT_TYPE);
	        $this->assign('patientType', $patientType);
	        $defaultType   =   Utils::getEnumKey(EnumerationConstant::PATIENT_TYPE, EnumerationConstant::PATIENT_TYPE_OUTPATIENT);
	        $this->assign('defaultType', $defaultType);
	        $html  = $this->view->render('queue.html');
    	}
    	catch(EnumException $ex) {
            $this->logger->error('Action RenderQueue fail. Error message: '. $ex->getMessage());
    	}
    	catch(Exception $ex) {
    		$this->logger->error('Action RenderQueue fail. Error message: '. $ex->getMessage());
    	}
        $this->logger->info("Finish action renderQueue");
    	return $html;
    }

    public function actionRenderQueueAjax() {
        $result = array(
                    'error'     =>  array('code'=>CoreErrorCode::NORMAL, 'mess'=>''),
                    'result'    =>  ''
        );
    	$roomId =   $_GET['roomId'];
        $enumPatientType    =   $_GET['patientType'];
    	$this->logger->info("Start action renderQueueAjax {roomId=$roomId, enumPatientType=$enumPatientType}");
    	try {
            $result['result']    =   RadQueueProcessor::renderQueue($roomId, $enumPatientType);
    	}
    	catch (Exception $e) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error("Action RenderQueueAjax fail. Error message:" . $e->getMessage());
    	}
    	$this->logger->info("Finish action renderQueueAjax {roomId=$roomId, enumPatientType=$enumPatientType}");

    	return json_encode($result);
    }

    public function actionCancelQueueItemAjax() {
        $result = array(
                    'error'     =>  array('code'=>CoreErrorCode::NORMAL, 'mess'=>''),
                    'result'    =>  ''
        );
        $radTicketId    =   $_GET['radTicketId'];
        $this->logger->info("Start action CancelQueueItemAjax {radTicketId=$radTicketId}");
        try {
        	// Check if the rad ticket has result
            $objRadTicket       =   ORDataObject::factory('RadTicket');
            if ($objRadTicket->hasItemDone($radTicketId)) {
            	throw new RadException("The radiology ticket [radTicketId=$radTicketId] has some items done", RadErrorCode::TICKET_HAS_ITEM_DONE);
            }

        	// Move queue item to waiting queue
            RadQueueProcessor::moveQueueItem($radTicketId, ARadQueue::QUEUE_TYPE_WAITING);

            // Get appreciate rad connector
            $objRadTicket->setup($radTicketId);
            $enumPatientType    =   $objRadTicket->getEnumPatientType();
            $objRadConnector    =   RadConnectorFactory::createConnector($enumPatientType);
            $objRadConnector->doAfterCancelAssignment($radTicketId, RadUtils::convertToTicketItemType($objRadTicket->getEnumRadType()));
        }
        catch (RadException $e) {
        	$result['error']['code'] = $e->getErrorCode();
            $result['error']['mess'] = RadErrorCode::getErrorMess($e->getErrorCode());
            $this->logger->error("Action CancelQueueItemAjax fail. Error message:" . $e->getMessage());
        }
        catch (Exception $e) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error("Action CancelQueueItemAjax fail. Error message:" . $e->getMessage());
        }
        $this->logger->info("Finish action CancelQueueItemAjax {radTicketId=$radTicketId}");

        return json_encode($result);
    }

    public function actionFinishQueueItemAjax($radTicketId = 0) {
        $result = array(
                    'error'     =>  array('code'=>CoreErrorCode::NORMAL, 'mess'=>''),
                    'result'    =>  ''
        );
        if (isset($_GET['radTicketId'])) {
            $radTicketId    =   $_GET['radTicketId'];
        }
        $this->logger->info("Start action FinishQueueItemAjax {radTicketId=$radTicketId}");
        try {
            // Remove queue item
        	ARadQueue::removeQueueItem($radTicketId);

        	// Set status of the rad ticket to done
        	$objRadTicket  =   Celini::newORDO('RadTicket', $radTicketId);
        	$objRadTicket->updateTicketStatus($radTicketId,
                Utils::getEnumKey(EnumerationConstant::RAD_TICKET_STATUS, EnumerationConstant::RAD_TICKET_STATUS_DONE));

            // Get approciate connector
	        $enumPatientType    =   $objRadTicket->getEnumPatientType();
            $objRadConnector    =   RadConnectorFactory::createConnector($enumPatientType);
	        // Call doAfterFinishTicket action of connector
	        $prices    =   $objRadTicket->getPriceInfo($radTicketId);
	        $objRadConnector->doAfterFinishAssignment($radTicketId,
	           RadUtils::convertToTicketItemType($objRadTicket->getEnumRadType()), $prices);
        }
        catch (Exception $e) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error("Action CancelQueueItemAjax fail. Error message:" . $e->getMessage());
        }
        $this->logger->info("Finish action FinishQueueItemAjax {radTicketId=$radTicketId}");

        return json_encode($result);
    }
}
?>